package com.scau.controller;

import com.scau.common.message.ResponseMessage;
import com.scau.common.util.MessageUtil;
import com.scau.entity.ClassSchedule;
import com.scau.entity.Student;
import com.scau.entity.Teacher;
import com.scau.service.ClassScheduleService;
import com.scau.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("classSchedules")
public class ClassScheduleController {

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ClassScheduleService classScheduleService;

    @RequestMapping(value = "createAll", method = RequestMethod.POST)
    public ResponseMessage<String> createAll(@RequestBody List<ClassSchedule> classSchedules) {

        for (ClassSchedule classSchedule : classSchedules) {
            String[] teacherName = new String[classSchedule.getTeacher().length];
            String[] className = new String[classSchedule.getTeacher().length];

            for(int i=0;i<classSchedule.getTeacher().length;i++) {
                if (classSchedule.getTeacher()[i]==0) {
                    className[i]="";
                    teacherName[i]="";
                    continue;
                }
                Teacher teacher = teacherService.findOne(classSchedule.getTeacher()[i]);
                teacherName[i]=teacher.getName();
                className[i]=teacher.getSubject();
            }
            classSchedule.setTeacherName(teacherName);
            classSchedule.setClassName(className);
        }

        classScheduleService.addAll(classSchedules);

        return MessageUtil.getSuccessMessage();
    }

    @RequestMapping(method = RequestMethod.GET)
    public ResponseMessage<Page<ClassSchedule>> list(ClassSchedule classSchedule, Pageable pageable) {

        Page<ClassSchedule> classSchedules = classScheduleService.findAll(classSchedule, pageable);

        return MessageUtil.getSuccessMessage(classSchedules);
    }

    @RequestMapping(value = "/{classScheduleId}", method = RequestMethod.GET)
    public ResponseMessage<ClassSchedule> get(@PathVariable Long classScheduleId) {

        ClassSchedule classSchedule = classScheduleService.findOne(classScheduleId);
        return MessageUtil.getSuccessMessage(classSchedule);
    }

    @Scheduled(cron = "0 0 * * * ?")
    public void scheduling() {
        classScheduleService.finishedClass();
    }
}
